package com.yao.club.service.impl;

import com.yao.club.entity.dto.*;
import com.yao.club.entity.request.MallGoodsSearchRequest;
import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.entity.result.ResultEntity;
import com.yao.club.entity.vo.GoodsAttrValueVO;
import com.yao.club.entity.vo.MallSearchSuggestionVO;
import com.yao.club.entity.vo.GoodsDetailVO;
import com.yao.club.entity.vo.SpecAttrVO;
import com.yao.club.reposittory.GoodsBrandRepository;
import com.yao.club.reposittory.MallGoodsInfoRepository;
import com.yao.club.reposittory.MallHotWordsRepository;
import com.yao.club.reposittory.GoodsMainRepository;
import com.yao.club.reposittory.GoodsSkuRepository;
import com.yao.club.reposittory.GoodsAttrRepository;
import com.yao.club.reposittory.GoodsAttrValueRepository;
import com.yao.club.service.MallSearchService;
import com.yao.club.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    private MallHotWordsRepository mallHotWordsRepository;
    @Autowired
    private GoodsBrandRepository goodsBrandRepository;
    @Autowired
    private MallGoodsInfoRepository mallGoodsInfoRepository;


    /**
     * 获得热门搜索推荐
     */
    @Override
    public ResponseEntity<List<MallHotWords>> getHotWords() {
        List<MallHotWords> all = mallHotWordsRepository.findAll();
        if (all == null) {
            return ResponseUtils.failed("失败");
        }
        return ResponseUtils.success(all);
    }
    /**
     * 根据关键字搜索品牌
     */
    @Override
    public ResponseEntity<List<GoodsBrand>> getBrandsByKeyWords(String keyword) {
        List<GoodsBrand> goodsBrandsByBrandNameLike = goodsBrandRepository.findGoodsBrandsByBrandNameContaining(keyword);
        if (goodsBrandsByBrandNameLike == null) {
            return ResponseUtils.failed("失败");
        }
        return ResponseUtils.success(goodsBrandsByBrandNameLike);
    }

    @Override
    public ResponseEntity<ResultEntity<MallGoodsInfo>> searchGoods(MallGoodsSearchRequest request) {
        try {
            // 构建查询条件
            Specification<MallGoodsInfo> specification = (root, query, criteriaBuilder) -> {
                List<Predicate> predicates = new ArrayList<>();
                
                // 关键词搜索
                if (request.getKeyWord() != null && !request.getKeyWord().isEmpty()) {
                    predicates.add(criteriaBuilder.or(
                        criteriaBuilder.like(root.get("title"), "%" + request.getKeyWord() + "%"),
                        criteriaBuilder.like(root.get("brandName"), "%" + request.getKeyWord() + "%")
                    ));
                }

                // 价格范围
                if (request.getMinMoney() != null && request.getMinMoney() != 0) {
                    predicates.add(criteriaBuilder.ge(root.get("marketPriceFee"), request.getMinMoney()));
                }
                if (request.getMaxMoney() != null && request.getMaxMoney() != 0) {
                    predicates.add(criteriaBuilder.le(root.get("marketPriceFee"), request.getMaxMoney()));
                }

                // 只查询上架的商品
//                predicates.add(criteriaBuilder.equal(root.get("status"), 1));
                
                return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
            };

            // 构建排序
            Sort sort = createSort(request.getSortKey(), request.getSort());
            
            // 构建分页
            int pageNumber = request.getStart() != null ? request.getStart() - 1 : 0;
            int pageSize = request.getLimit() != null ? request.getLimit() : 10;
            PageRequest pageRequest = PageRequest.of(pageNumber, pageSize, sort);

            // 执行查询
            Page<MallGoodsInfo> page = mallGoodsInfoRepository.findAll(specification, pageRequest);

            // 构建返回结果
            ResultEntity<MallGoodsInfo> result = new ResultEntity<>();
            result.setRecords(page.getContent());
            result.setTotal((int) page.getTotalElements());
            result.setSize(page.getSize());
            result.setCurrent(page.getNumber() + 1);
            result.setPages(page.getTotalPages());

            return ResponseUtils.success(result);
        } catch (Exception e) {
            return ResponseUtils.failed("商品搜索失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseEntity<List<MallSearchSuggestionVO>> goodsSearchKeywordList(String keyword) {

        List<MallGoodsInfo> mallGoodsInfoByTitleLike = mallGoodsInfoRepository.findMallGoodsInfosByTitleContaining(keyword);
        if (mallGoodsInfoByTitleLike != null) {
            List<MallSearchSuggestionVO> mallSearchSuggestionVOS = new ArrayList<>();
            for (MallGoodsInfo mallGoodsInfo : mallGoodsInfoByTitleLike) {
                MallSearchSuggestionVO mallSearchSuggestionVO = new MallSearchSuggestionVO();
                mallSearchSuggestionVO.setName(mallGoodsInfo.getTitle());
                mallSearchSuggestionVO.setGoodsId(mallGoodsInfo.getId()+"");
                mallSearchSuggestionVOS.add(mallSearchSuggestionVO);
            }
            return ResponseUtils.success(mallSearchSuggestionVOS);
        }
        return ResponseUtils.failed("失败");
    }

    @Override
    public ResponseEntity<List<GoodsBrand>> mallGoodsListAllCondition() {
        return ResponseUtils.success(goodsBrandRepository.findAll());
    }

    private Sort createSort(String sortKey, String sortDirection) {
        Sort.Direction direction = "desc".equalsIgnoreCase(sortDirection) ? 
            Sort.Direction.DESC : Sort.Direction.ASC;

        switch (sortKey) {
            case "soldNumSort":
                return Sort.by(direction, "soldNum");
            case "newGoodsSort":
                return Sort.by(direction, "createTime");
            case "priceSort":
                return Sort.by(direction, "marketPriceFee");
            default:
                return Sort.by(Sort.Direction.DESC, "createTime"); // 默认按创建时间降序
        }
    }


}
